package com.example.aigc_education.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.agentsflex.llm.spark.SparkLlm;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.constant.CacheConstants;
import com.example.aigc_education.domain.Theme;
import com.example.aigc_education.domain.dto.*;
import com.example.aigc_education.domain.request.AddFlashCardsRequest;
import com.example.aigc_education.domain.request.AddQuizzesRequest;
import com.example.aigc_education.domain.request.SaveOrSubmitQuizRequest;
import com.example.aigc_education.domain.vo.*;
import com.example.aigc_education.enums.*;
import com.example.aigc_education.integration.response.workflows.v2.CozeGenFlashCResponse;
import com.example.aigc_education.integration.response.workflows.v2.CozeGenQuizzesResponse;
import com.example.aigc_education.mapper.ThemeMapper;
import com.example.aigc_education.service.converter.PaperConverter;
import com.example.aigc_education.domain.Paper;
import com.example.aigc_education.domain.PaperQuestion;
import com.example.aigc_education.domain.Question;
import com.example.aigc_education.domain.request.SaveFlashCardListRequest;
import com.example.aigc_education.mapper.PaperQuestionMapper;
import com.example.aigc_education.mapper.QuestionMapper;
import com.example.aigc_education.service.PaperService;
import com.example.aigc_education.mapper.PaperMapper;
import com.example.aigc_education.utils.JsonUtils;
import com.example.aigc_education.utils.RedisCache;
import com.example.aigc_education.utils.SecurityUtils;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 23918
* @description 针对表【stu_paper】的数据库操作Service实现
* @createDate 2024-06-20 10:48:39
*/
@Service
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper>
    implements PaperService{

    @Resource
    private PaperMapper paperMapper;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private PaperQuestionMapper paperQuestionMapper;

    @Resource
    private ThemeMapper themeMapper;

    @Resource
    private SparkLlm sparkLlm;

    @Resource
    private PaperConverter paperConverter;

    @Resource
    private RedisCache redisCache;

    @Transactional
    @Override
    public List<QuestionVO> generatePaper(Long paperId,
                                          GenPaperRuleDTO genPaperRuleDTO) {


        List<QuestionVO> questionVOList = new ArrayList<>();
        Map<String, Map<String, Integer>> ruleTable = parseRuleTable(genPaperRuleDTO.getRuleTable());

        List<String> knowledgePointers = genPaperRuleDTO.getKnowledgePointers();
        List<QuestionVO> resQuestions = new ArrayList<>();

        // 打印结果
        for (Map.Entry<String, Map<String, Integer>> entry : ruleTable.entrySet()) {
            System.out.println("题目类型：" + entry.getKey());
            int questionType = showQuestionType(entry.getKey());
            for (Map.Entry<String, Integer> subEntry : entry.getValue().entrySet()) {
                System.out.println("题目难度：" + subEntry.getKey() + " 题目数量：" + subEntry.getValue());
                if (subEntry.getValue() > 0) {
                    int questionDifficulty = showQuestionDifficulty(subEntry.getKey());

                    List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                            .eq(Question::getType, questionType)
                            .eq(Question::getDifficulty, questionDifficulty)
                            .eq(Question::getStatus, 1)
                            .eq(Question::getComposeFlag, 1)
                            .last("LIMIT " + subEntry.getValue()));

                    for (Question question : questions) {
                        QuestionVO questionVO = new QuestionVO();
                        questionVO.setQuestionId(question.getQuestionId());
                        questionVO.setType(question.getType());
                        questionVO.setContent(question.getContent());
                        questionVO.setAnswer(question.getAnswer());
                        questionVO.setDifficulty(question.getDifficulty());
                        questionVO.setOptions(question.getOptions());
                        questionVO.setKnowledgePoint(question.getKnowledgePoint());
                        questionVO.setCorrectAnswers(question.getCorrectAnswers());
                        questionVO.setName(question.getName());
                        questionVOList.add(questionVO);
                    }
                }

            }
        }

        for (String knowledgePoint : knowledgePointers) {
            for (QuestionVO questionVO : questionVOList) {
                String res = judgeQuestionIsSuitable(knowledgePoint, questionVO.getContent());
                if (res.contains("true")) {
                    resQuestions.add(questionVO);
                    // paper 与 question 关联，插入paper_question表
                    PaperQuestion paperQuestion = new PaperQuestion();
                    paperQuestion.setPaperId(paperId);
                    paperQuestion.setQuestionId(questionVO.getQuestionId());
                    paperQuestion.setStatus(1);
                    int resSQl = paperQuestionMapper.insert(paperQuestion);
                    if (resSQl == 0) {
                        throw new BusinessException("试卷与题目关联失败");
                    }
                }
            }
        }

        return resQuestions;
    }



    @Transactional
    @Override
    public QuestionVO updatePaper(Long questionId, Long paperId) {
        LambdaQueryWrapper<PaperQuestion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaperQuestion::getPaperId, paperId);
        List<PaperQuestion> paperQuestions = paperQuestionMapper.selectList(queryWrapper);

        List<Long> questionIds = paperQuestions.stream()
                .map(PaperQuestion::getQuestionId)
                .distinct()
                .collect(Collectors.toList());

        Question question = questionMapper.selectById(questionId);

        LambdaQueryWrapper<Question> paperQueryWrapper = new LambdaQueryWrapper<>();
        paperQueryWrapper.eq(Question::getComposeFlag, 1)
                .notIn(Question::getQuestionId, questionIds);

        List<Question> selectedQuestions = questionMapper.selectList(paperQueryWrapper);
        QuestionVO res = null;
        for (Question selectedQuestion : selectedQuestions) {
            String judged = judgeQuestionIsSuitable(question.getKnowledgePoint(), selectedQuestion.getContent());
            if (judged.contains("true")) {
                PaperQuestion paperQuestion = new PaperQuestion();
                paperQuestion.setPaperId(paperId);
                paperQuestion.setQuestionId(selectedQuestion.getQuestionId());
                paperQuestion.setStatus(1);
                // 是否要插入paper_question表
                paperQuestionMapper.insert(paperQuestion);
                res = BeanUtil.toBean(selectedQuestion, QuestionVO.class);
                break;
            }
        }
        if (res != null) {
            PaperQuestion PQ = paperQuestionMapper.selectById(paperId);
            PQ.setStatus(0);
            paperQuestionMapper.updateById(PQ);
        }

        return res;
    }

    // 展示题目难度
    private int showQuestionDifficulty(String difficulty) {
        //题目难度 容易：0， 较易：1， 中等：2， 较难：3， 困难：4
        switch (difficulty) {
            case "较易":
                return 1;
            case "中等":
                return 2;
            case "较难":
                return 3;
            case "困难":
                return 4;
            case "容易":
            default:
                return 0;
        }
    }

    // 展示题目类型
    private int showQuestionType(String type) {
        switch (type) {
            case "多项选择题":
                return 1;
            case "判断题":
                return 3;
            case "填空题":
                return 2;
            case "解答题":
                return 4;
            case "单项选择题":
            default:
                return 0;
        }
    }

    private Map<String, Map<String, Integer>> parseRuleTable(String[][] table) {
        Map<String, Map<String, Integer>> questionMap = new HashMap<>();
        // 获取题目难度列表
        String[] difficulties = table[0];

        for (int i = 1; i < table.length; i++) {
            String questionType = table[i][0];
            Map<String, Integer> difficultyMap = new HashMap<>();
            for (int j = 1; j < table[i].length; j++) {
                difficultyMap.put(difficulties[j - 1], Integer.parseInt(table[i][j]));
            }
            questionMap.put(questionType, difficultyMap);
        }

        return questionMap;
    }

    // output: true or false
    private String judgeQuestionIsSuitable(String knowledgePoint, String question) {
        String prompt = "你根据用户给你的问题和知识点，判断该问题是否属于该知识点，是则返回true,否则返回false，不用作任何解释，不用对提问内容重新展示，只需要输出true或者false。提问格式为：问题:知识点。响应格式为：true\n";
        String knowPrompt = question + ":" + knowledgePoint;
        try {
            return sparkLlm.chat(prompt + knowPrompt);
        } catch (Exception e) {
            throw new BusinessException("调用AI接口失败");
        }
    }


    /**
     * 添加试卷信息
     *
     * 本方法通过调用paperMapper的insert方法，将传入的试卷对象插入到数据库中。
     * 如果插入操作失败，即捕获到异常，方法将抛出一个业务异常，指示添加试卷失败。
     * 这样做的目的是为了确保数据的正确性和一致性，以及在出现问题时能够及时地给出反馈。
     *
     * @param paper 待添加的试卷对象，包含试卷的所有相关信息。
     * @throws BusinessException 如果添加试卷过程中发生异常，则抛出此异常。
     */
    @Override
    @Transactional
    public void addPaper(Paper paper){
        try {
            paperMapper.insert(paper);
        } catch (Exception e) {
            throw new BusinessException("添加试卷失败");
        }
    }

    /**
     * 根据paperId更新Paper对象的信息。
     * 此方法尝试更新数据库中与给定paperId匹配的试卷的信息。如果更新过程中发生异常，
     * 则会抛出一个自定义的业务异常，提示更新试卷失败。
     *
     * @param paper 包含待更新试卷信息的对象。
     * @param paperId 需要更新的试卷的唯一标识ID。
     * @throws BusinessException 如果更新操作失败，抛出此异常。
     */
    @Override
    @Transactional
    public void updatePaper(Paper paper, Long paperId){
        try {

            // 创建UpdateWrapper用于构建更新条件，这里指定根据paperId进行更新。
            UpdateWrapper<Paper> wrapper = new UpdateWrapper<>();
            wrapper.eq("paper_id", paperId);
            // 调用paperMapper的update方法，传入新的试卷对象和更新条件，执行更新操作。
            paperMapper.update(paper, wrapper);
        } catch (Exception e) {
            // 如果更新过程中发生异常，抛出运行时异常，并提示更新试卷失败。
            throw new BusinessException("更新试卷失败");
        }
    }

    @Override
    @Transactional
    public void deletePaper(Long paperId){
        try {
            paperMapper.deleteById(paperId);
        } catch (Exception e) {
            throw new BusinessException("删除试卷失败");
        }
    }

    /**
     * 查询所有试卷信息
     *
     * 本方法尝试通过调用paperMapper的selectById方法来查询指定ID的试卷信息。
     * 如果查询过程中发生异常，方法将抛出一个自定义的业务异常，指示查询试卷失败。
     * 这种方式确保了对查询操作的异常进行捕获和处理，使得调用方可以更方便地处理可能的错误情况。
     *
     * @throws BusinessException 如果查询试卷过程中发生异常，则抛出此异常，异常信息为"查询试卷失败"。
     */
    @Override
    public List<Paper> selectPaper(){
        try {
            List<Paper> papers = paperMapper.selectList(null);
            return papers;
        } catch (Exception e) {
            throw new BusinessException("查询试卷失败");
        }
    }

    @Override
    public List<BriefFlashCardListVO> showAllFlashCardList(Long themeId) {
        try {
            LambdaQueryWrapper<Paper> queryWrapper = new LambdaQueryWrapper<>();
            //通过主题id筛选paper
            queryWrapper.eq(Paper::getThemeId, themeId);
            //筛选出抽记卡
            queryWrapper.eq(Paper::getPaperType, 1);
            //筛选出有效的抽认卡
            queryWrapper.eq(Paper::getStatus, 1);
            // 根据创建日期升序排序
            queryWrapper.orderByAsc(Paper::getCreateTime);
            List<Paper> papers = paperMapper.selectList(queryWrapper);
            // 转换成VO
            List<BriefFlashCardListVO> briefFlashCardListVOS = paperConverter.papersToBriefFlashCardListVOs(papers);
            return briefFlashCardListVOS;
        } catch (Exception e) {
            throw new BusinessException("查询抽记卡集合失败");
        }
    }

    @Override
    public EntireFlashCardListVO getEntireFlashCardList(Long flashCardListId) {
        try {
            Paper paper = paperMapper.selectById(flashCardListId);
            EntireFlashCardListVO entireFlashCardListVO = paperConverter.paperToEntireFlashCardListVO(paper);
            return entireFlashCardListVO;

        } catch (Exception e) {
            throw new BusinessException("查询抽记卡集合失败");
        }
    }



    @Override
    public boolean saveFlashCardList(SaveFlashCardListRequest saveFlashCardListRequest) {
        try {
            //通过id寻找到抽认卡集
            Long flashCardListId = saveFlashCardListRequest.getFlashCardListId();
            Paper paper = paperMapper.selectById(flashCardListId);
            //将用户回答状态存入数据库
            String questionsJson = JSON.toJSONString(saveFlashCardListRequest.getFlashCardDTOS());
            paper.setQuestions(questionsJson);
            paperMapper.updateById(paper);
            return true;
        } catch (Exception e) {
            throw new BusinessException("提交抽记卡集合失败");
        }
    }

    @Override
    public boolean submitFlashCardList(SaveFlashCardListRequest saveFlashCardListRequest) {
        try {
            //通过id寻找到抽认卡集
            Long flashCardListId = saveFlashCardListRequest.getFlashCardListId();
            Paper paper = paperMapper.selectById(flashCardListId);
            //将用户回答状态存入数据库
            Integer correctNum = 0;
            Integer wrongNum = 0;
            Integer forgetNum = 0;
            for (FlashCardDTO flashCardDTO : saveFlashCardListRequest.getFlashCardDTOS()) {
                if (flashCardDTO.getAnswerStatus() == 1){
                    correctNum++;
                }else if (flashCardDTO.getAnswerStatus() == 2){
                    wrongNum++;
                }else if (flashCardDTO.getAnswerStatus() == 3){
                    forgetNum++;
                }
            }
            String stringAnswerStatus = correctNum + "," + wrongNum + "," + forgetNum;
            paper.setAnswerStatus(stringAnswerStatus);
            //将用户回答状态存入数据库
            String questionsJson = JSON.toJSONString(saveFlashCardListRequest.getFlashCardDTOS());
            paper.setQuestions(questionsJson);
            //试卷变为已完成
            paper.setIsComplete(1);
            paperMapper.updateById(paper);
            return true;
        } catch (Exception e) {
            throw new BusinessException("提交抽记卡集合失败");
        }
    }


    /**
     * 抽认卡软删除
     * @param flashCardListId 抽认卡id
     * @return true
     */
    @Override
    public boolean deleteFlashCardList(Long flashCardListId) {
        Paper paper = paperMapper.selectById(flashCardListId);
        paper.setStatus(0);
        paperMapper.updateById(paper);
        return true;
    }


    @Override
    public List<BriefQuizVO> showAllQuiz(Long themeId) {
        try {
            LambdaQueryWrapper<Paper> queryWrapper = new LambdaQueryWrapper<>();
            //通过主题id筛选paper
            queryWrapper.eq(Paper::getThemeId, themeId);
            //筛选出测验
            queryWrapper.eq(Paper::getPaperType, 0);
            //筛选出有效的测验
            queryWrapper.eq(Paper::getStatus, 1);
            // 根据创建日期升序排序
            queryWrapper.orderByAsc(Paper::getCreateTime);
            List<Paper> papers = paperMapper.selectList(queryWrapper);
            // 转换成VO
            List<BriefQuizVO> briefQuizVOS = paperConverter.papersToBriefQuizVOS(papers);
            return briefQuizVOS;
        } catch (Exception e) {
            throw new BusinessException("查询测验失败");
        }
    }

    @Override
    public EntireQuizVO getEntireQuiz(Long quizId) {
        try {
            Paper paper = paperMapper.selectById(quizId);
            EntireQuizVO entireQuizVO = paperConverter.paperToEntireQuizVO(paper);
            return entireQuizVO;

        } catch (Exception e) {
            throw new BusinessException("查询测验集合失败");
        }
    }

    @Override
    public boolean saveQuiz(SaveOrSubmitQuizRequest saveOrSubmitQuizRequest) {
        try {
            //通过id寻找到测验
            Long quizId = saveOrSubmitQuizRequest.getQuizId();
            Paper paper = paperMapper.selectById(quizId);
            // 将问题集合串转为JSON字符串
            String questionsJson = JSON.toJSONString(saveOrSubmitQuizRequest.getQuizQuestionDTOS());
            paper.setQuestions(questionsJson);
            paperMapper.updateById(paper);
            return true;
        } catch (Exception e) {
            throw new BusinessException("保存测验失败");
        }
    }


    @Override
    public boolean submitQuiz(SaveOrSubmitQuizRequest saveOrSubmitQuizRequest) {
        try {
            //通过id寻找到测验
            Long quizId = saveOrSubmitQuizRequest.getQuizId();
            Paper paper = paperMapper.selectById(quizId);
            //将用户回答状态存入数据库
            Integer correctNum = 0;
            Integer wrongNum = 0;
            for (QuizQuestionDTO quizQuestionDTO : saveOrSubmitQuizRequest.getQuizQuestionDTOS()) {
                if (quizQuestionDTO.getQuestionType().equals("filling") && quizQuestionDTO.getUserAnswer().equals(quizQuestionDTO.getAnswer())){
                    Short correct = 1;
                    quizQuestionDTO.setAnswerStatus(correct);
                    correctNum++;
                } else if (!quizQuestionDTO.getQuestionType().equals("filling")) {
                    // 将List转换为Multiset
                    Multiset<String> userAnswer = HashMultiset.create(quizQuestionDTO.getUserAnswer());
                    Multiset<String> answer = HashMultiset.create(quizQuestionDTO.getAnswer());

                    // 比较两个Multiset的内容是否相同
                    boolean areEqual = userAnswer.equals(answer);
                    if (areEqual) {
                        Short correct = 1;
                        quizQuestionDTO.setAnswerStatus(correct);
                        correctNum++;
                    } else {
                        Short wrong = 2;
                        quizQuestionDTO.setAnswerStatus(wrong);
                        wrongNum++;
                    }

                } else {
                    Short wrong = 2;
                    quizQuestionDTO.setAnswerStatus(wrong);
                    wrongNum++;
                }
            }
            //整张试卷回答状态
            String stringAnswerStatus = correctNum + "," + wrongNum;
            paper.setAnswerStatus(stringAnswerStatus);
            // 将问题集合串转为JSON字符串
            String questionsJson = JSON.toJSONString(saveOrSubmitQuizRequest.getQuizQuestionDTOS());
            paper.setQuestions(questionsJson);
            //试卷变为已完成
            paper.setIsComplete(1);
            paperMapper.updateById(paper);
            return true;
        } catch (Exception e) {
            throw new BusinessException("提交测验失败");
        }
    }

    @Override
    public boolean redoQuiz(Long quizId) {
        try {
            //查询出测验
            Paper paper = paperMapper.selectById(quizId);
            //拿出问题并反序列化为对象
            String questions = paper.getQuestions();
            List<QuizQuestionDTO> quizQuestionDTOS = JSON.parseArray(questions, QuizQuestionDTO.class);
            for (QuizQuestionDTO quizQuestionDTO : quizQuestionDTOS) {
                //将用户本次答案设为上次答案,用户本次答案为空字符串
                quizQuestionDTO.setLastAnswer(quizQuestionDTO.getUserAnswer());
                quizQuestionDTO.setUserAnswer(new ArrayList<>());
                //设置用户回答问题状态为未做
                Short noDo = 0;
                quizQuestionDTO.setAnswerStatus(noDo);
            }
            //设置整张试卷回答状态
            paper.setAnswerStatus("0,0");
            String questionsJson = JSON.toJSONString(quizQuestionDTOS);
            paper.setQuestions(questionsJson);
            //试卷变为未完成
            paper.setIsComplete(0);
            paperMapper.updateById(paper);
            return true;
        } catch (Exception e) {
            throw new BusinessException("重做测验失败");
        }
    }


    @Override
    public boolean deleteQuiz(Long quizId) {
        Paper paper = paperMapper.selectById(quizId);
        paper.setStatus(0);
        paperMapper.updateById(paper);
        return true;
    }

    @Override
    public Long batchSaveQuiz(AddQuizzesRequest request) {

        LambdaQueryWrapper<Theme> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Theme::getThemeId, request.getThemeId());
        Long aLong = themeMapper.selectCount(queryWrapper);
        if (aLong == 0) {
            throw new BusinessException("主题不存在");
        }

        //添加试卷逻辑
        Paper paper = new Paper();
        paper.setThemeId(request.getThemeId());
        paper.setPaperName(request.getPaperName());
        paper.setDifficulty(PaperDifficultyType.fromTitle(request.getDifficulty()).getValue());
        paper.setPaperType(PaperUseType.EXAM.getValue());
        paper.setLanguage(LanguageType.CHINESE.getValue());
        paper.setAnswerStatus(UserAnswerStatus.QUIZZES_STATUS.getStatus());
        paper.setQuestionNum(request.getQuizzes().size());
        //添加试卷里的问题集合逻辑
        List<QuizQuestionDTO> questionV2DTOs =  new ArrayList<>();
        Integer questionNO = 1;
        for (AddQuizzesRequest.Quiz quiz : request.getQuizzes()) {
            QuizQuestionDTO quizQuestionDTO = BeanUtil.copyProperties(quiz, QuizQuestionDTO.class);
            System.out.println(quiz.getAnswer());
            System.out.println(quizQuestionDTO.getAnswer());
            quizQuestionDTO.setQuestionNo(questionNO);
            questionNO++;
            quizQuestionDTO.setAnswerStatus((short) AnswerStatus.INIT.getValue());
            quizQuestionDTO.setOptions(JSON.toJSONString(quiz.getOptions()));
            //设为空集合
            quizQuestionDTO.setUserAnswer(new ArrayList<>());
            quizQuestionDTO.setLastAnswer(new ArrayList<>());
            questionV2DTOs.add(quizQuestionDTO);
        }
        paper.setQuestions(JSON.toJSONString(questionV2DTOs));
        int insert = paperMapper.insert(paper);

        //添加后修改缓存
        Long userId = SecurityUtils.getUserId();
        String key = CacheConstants.USER_GEN_QUIZ_KEY + userId;
        Map<String, CozeGenQuizzesResponse> quizCache = redisCache.getCacheObject(key);
        quizCache.remove(request.getExecuteId());
        redisCache.setCacheObject(key, quizCache);

        if (insert == 0) {
            return null;
        }
        return paper.getPaperId();
    }

    @Override
    public boolean batchSaveFlashCards(AddFlashCardsRequest request) {
        LambdaQueryWrapper<Theme> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Theme::getThemeId, request.getThemeId());
        Long aLong = themeMapper.selectCount(queryWrapper);
        if (aLong == 0) {
            throw new BusinessException("主题不存在");
        }

        Paper paper = new Paper();
        paper.setThemeId(request.getThemeId());
        paper.setPaperName(request.getPaperName());
        paper.setDifficulty(PaperDifficultyType.fromTitle(request.getDifficulty()).getValue());
        paper.setPaperType(PaperUseType.FLASHCARD.getValue());
        paper.setLanguage(LanguageType.CHINESE.getValue());
        paper.setAnswerStatus(UserAnswerStatus.FLASHCARD_STATUS.getStatus());
        paper.setQuestionNum(request.getFlashCards().size());
//        //将生产的抽认卡集合保存到数据库
        List<AddFlashCardsRequest.FlashCard> flashCards = request.getFlashCards();
        List<FlashCardDTO> flashCardDTOS = new ArrayList<>();
        int questionNo = 1;
        for (AddFlashCardsRequest.FlashCard flashCard : flashCards) {
            FlashCardDTO flashCardDTO = new FlashCardDTO();
            flashCardDTO.setQuestionNo(questionNo);
            questionNo++;
            flashCardDTO.setContent(flashCard.getCard_question());
            flashCardDTO.setAnswerDescription(flashCard.getCard_answer());
            flashCardDTO.setAnswerStatus((short) AnswerStatus.INIT.getValue());
            //在集合中添加并按问题编号排序
            flashCardDTOS.add(flashCardDTO);
        }
        flashCardDTOS.sort(Comparator.comparingInt(FlashCardDTO::getQuestionNo));
        //转为JSON字符串
        String flashCardsJson = JsonUtils.toJson(flashCardDTOS);
        paper.setQuestions(flashCardsJson);
        int insert = paperMapper.insert(paper);

        //添加后修改缓存
        Long userId = SecurityUtils.getUserId();
        String key = CacheConstants.USER_GEN_FLASH_KEY + userId;
        Map<String, CozeGenFlashCResponse> flashCache = redisCache.getCacheObject(key);
        flashCache.remove(request.getExecuteId());
        redisCache.setCacheObject(key, flashCache);

        if (insert == 0) {
            return false;
        }
        return true;
    }
}




